<template>
  <div class="box-border w-full h-full task-setting">
    <div class="flex items-center gap-2 text-lg">
      <span class="text-[#030014]/60">模型管理</span>
      <span class="text-[#030014]/60">></span>
      <span class="text-[#030014]"> 上传模型</span>
    </div>
    <div
      class="target-upload box-border p-7 pb-10 bg-white/50 rounded-[12px] border_white mt-7 h-[calc(100%-460px)] w-[95%] mx-auto overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <!-- 基础信息部分 -->
      <div class="flex basic-info">
        <div class="text-[20px] font-bold">基础信息</div>
        <el-form ref="basicFormRef" :model="basicFormData" :rules="basicRules" label-width="120px">
          <el-form-item label="模型名称" prop="cname">
            <el-input
              v-model="basicFormData.cname"
              placeholder="请输入模型名称"
              class="!w-[400px]"
            />
          </el-form-item>
          <el-form-item label="检测目标" prop="pics">
            <div class="flex flex-col gap-2">
              <div
                v-for="(target, index) in basicFormData.pics"
                :key="index"
                class="flex items-start"
              >
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept="image/*"
                  @change="(file) => handleTargetImageUpload(file, index)"
                >
                  <div
                    v-if="!target.pic_url"
                    class="w-[50px] h-[50px] border border-dashed border-gray-300 flex items-center justify-center cursor-pointer"
                  >
                    <el-icon><Plus /></el-icon>
                  </div>
                </el-upload>

                <!-- 图片预览和操作区域 -->
                <div v-if="target.pic_url" class="flex flex-col items-center gap-1">
                  <el-image
                    :src="target.pic_url"
                    class="w-[50px] h-[50px] object-cover"
                    :preview-src-list="[target.pic_url]"
                    :initial-index="0"
                    fit="cover"
                    preview-teleported
                  />
                  <!-- 操作按钮 -->
                  <div class="flex items-center gap-4">
                    <el-upload
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      accept="image/*"
                      @change="(file) => handleTargetImageEdit(file, index)"
                    >
                      <el-icon class="text-lg text-gray-500 cursor-pointer hover:text-blue-500"
                        ><EditPen
                      /></el-icon>
                    </el-upload>
                    <el-popconfirm
                      title="确定要删除这张图片吗？"
                      @confirm="removeImg(index)"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      :teleported="false"
                    >
                      <template #reference>
                        <el-icon
                          class="mb-1 text-lg text-gray-500 cursor-pointer hover:text-red-500"
                        >
                          <Delete />
                        </el-icon>
                      </template>
                    </el-popconfirm>
                  </div>
                </div>

                <el-input
                  v-model="target.detect_target_cname"
                  placeholder="请输入目标名称"
                  class="!w-[332px] ml-4 mt-4"
                />
                <div class="flex items-center gap-2 mt-4 ml-4">
                  <el-popconfirm
                    title="确定要删除这个检测目标吗？"
                    @confirm="removeTarget(index)"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    :teleported="false"
                  >
                    <template #reference>
                      <div
                        class="flex items-center justify-center bg-white cursor-pointer w-7 h-7 border1 hover:text-red-500"
                      >
                        <el-icon class="text-lg text-gray-500"><Minus /></el-icon>
                      </div>
                    </template>
                  </el-popconfirm>
                  <div
                    v-if="index === basicFormData.pics.length - 1"
                    class="flex items-center justify-center bg-white cursor-pointer w-7 h-7 border1 hover:text-blue-500"
                    @click="addTarget"
                  >
                    <el-icon class="text-lg text-gray-500"><Plus /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 模型文件 -->
    <div
      class="p-7 video-settings w-[95%] mx-auto bg-white/50 rounded-[12px] border_white mt-7 h-[290px] box-border overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <div class="text-[20px] font-bold">模型文件</div>
      <el-form :model="fileFormData" label-width="120px">
        <el-form-item label="" prop="files">
          <el-upload
            v-model:file-list="fileFormData.files"
            class="mt-4 w-[85%] mx-auto"
            drag
            :show-file-list="false"
            :http-request="uploadModel"
            accept=".onnx,.hdf5,.tflite,.pt,.pkl,.bin,.json,.xml,.yaml"
            :multiple="false"
            :disabled="fileFormData.files.length >= 1"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text" v-if="fileFormData.files.length === 0">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__text" v-else>已上传文件，如需更换请先删除当前文件</div>
            <div class="text-[#606266] text-sm mt-2">
              文件扩展名：.onnx .hdf5 .tflite .pt .pkl .bin .json .xml .yaml...
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 文件列表显示部分 -->
      <div class="flex flex-wrap gap-4 mt-4">
        <div
          v-for="(file, index) in fileFormData.files"
          :key="index"
          class="flex items-center p-3 bg-white border rounded-md"
        >
          <img src="../assets/images/model_file.png" class="w-8 h-8 mr-2" />
          <span class="mr-2">{{ file.name }}</span>
          <el-popconfirm
            title="确定要删除这个模型文件吗？"
            @confirm="handleRemove(file)"
            confirm-button-text="确定"
            cancel-button-text="取消"
            :teleported="false"
          >
            <template #reference>
              <el-icon class="text-gray-400 cursor-pointer hover:text-red-500">
                <Delete />
              </el-icon>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <el-button type="primary" plain class="!w-[200px] !h-[40px]" @click="handleCancel"
        >退出</el-button
      >
      <el-button type="success" plain class="!w-[200px] !h-[40px]" @click="handleSave"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { UploadFilled, Plus, Minus, EditPen, Delete, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  createModel,
  uploadTargetImage,
  uploadModelFile,
  deleteImageOrModelFile,
} from '@/api/model'

const router = useRouter()

const basicFormRef = ref(null)
const fileFormData = ref({
  files: [],
})

// 拆分表单数据
const basicFormData = ref({
  cname: '',
  pics: [{ detect_target_cname: '', pic_url: '' }],
})

// 基础信息验证规则
const basicRules = {
  cname: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  pics: [
    {
      type: 'array',
      required: true,
      validator: (rule, value, callback) => {
        if (value.some((target) => !target.detect_target_cname || !target.pic_url)) {
          callback(new Error('请上传检测目标的图片和名称'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
}

// 添加新的目标
const addTarget = () => {
  basicFormData.value.pics.push({ detect_target_cname: '', pic_url: '' })
}

// 删除目标
const removeTarget = async (index) => {
  try {
    if (basicFormData.value.pics.length > 1) {
      // 只有当存在图片 URL 时才调用删除接口
      if (basicFormData.value.pics[index].pic_url) {
        await deleteImageOrModelFile({
          file_url: basicFormData.value.pics[index].pic_url.replace(
            import.meta.env.VITE_IMG_URL,
            '',
          ),
        })
      }
      basicFormData.value.pics.splice(index, 1)
      ElMessage.success('检测目标删除成功')
    } else {
      ElMessage.error('至少需要一个检测目标')
    }
  } catch (error) {
    ElMessage.error('检测目标删除失败')
  }
}

const handleTargetImageUpload = async (file, index) => {
  console.log('🐯 ~ handleTargetImageUpload ~ file:', file)
  try {
    const formData = new FormData()
    formData.append('pic_file', file.raw)

    // 调用上传API
    const res = await uploadTargetImage(formData)

    // 更新目标图片
    basicFormData.value.pics[index].pic_url = `${import.meta.env.VITE_IMG_URL}${res.data.file_path}`

    ElMessage.success('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
  }
}

const handleTargetImageEdit = async (file, index) => {
  try {
    // 先删除旧图片
    await deleteImageOrModelFile({
      file_url: basicFormData.value.pics[index].pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
    })

    // 上传新图片
    const formData = new FormData()
    formData.append('pic_file', file.raw)
    const res = await uploadTargetImage(formData)

    // 更新图片URL
    basicFormData.value.pics[index].pic_url = `${import.meta.env.VITE_IMG_URL}${res.data.file_path}`

    ElMessage.success('图片更新成功')
  } catch (error) {
    console.error('图片更新失败:', error)
    ElMessage.error('图片更新失败，请重试')
  }
}

const removeImg = async (index) => {
  try {
    await deleteImageOrModelFile({
      file_url: basicFormData.value.pics[index].pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
    })
    basicFormData.value.pics[index].pic_url = ''
    ElMessage.success('图片删除成功')
  } catch (error) {
    ElMessage.error('图片删除失败')
  }
}

const uploadModel = async (file) => {
  try {
    const formData = new FormData()
    formData.append('model_file', file.file)
    const response = await uploadModelFile(formData)
    const file_path = response.data.file_path
    fileFormData.value.files[0].model_url = file_path
    ElMessage.success('模型上传成功')
    setTimeout(() => {
      const container = document.querySelector('.video-settings')
      if (container) {
        container.scrollTo({
          top: container.scrollHeight,
          behavior: 'smooth',
        })
      }
    }, 100)
  } catch (error) {
    ElMessage.error('模型上传失败')
  }
}

const handleRemove = async (file) => {
  try {
    console.log('🐯 ~ handleRemove ~ file:', file)
    const index = fileFormData.value.files.indexOf(file)
    if (index !== -1) {
      await deleteImageOrModelFile({ file_url: file.model_url })
      fileFormData.value.files.splice(index, 1)
      ElMessage.success('模型文件删除成功')
    }
  } catch (error) {
    ElMessage.error('模型文件删除失败')
  }
}

const handleCancel = () => {
  // 处理退出逻辑
  router.go(-1)
}
const handleSave = async () => {
  try {
    // 只验证基础信息表单
    const basicValid = await basicFormRef.value?.validate().catch(() => false)

    // 模型文件使用 message 提示
    if (fileFormData.value.files.length === 0) {
      ElMessage.error('请上传模型文件')
      return
    }

    if (basicValid) {
      try {
        // 处理图片URL，移除基础路径
        const processedPics = basicFormData.value.pics.map((pic) => ({
          ...pic,
          pic_url: pic.pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
        }))

        await createModel({
          cname: basicFormData.value.cname,
          pics: processedPics,
          model_url: fileFormData.value.files[0].model_url,
          original_file_name: fileFormData.value.files[0].name,
        })
        ElMessage.success('模型文件上传成功')
        router.push('/model_home')
      } catch (error) {
        ElMessage.error('模型文件上传失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}
</script>

<style scoped>
.task-setting {
  padding: 20px 60px;

  .targets-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 50px;
    margin-top: 20px;
  }

  .target-item {
    .image-placeholder {
      width: 88px;
      height: 56px;
      background: #f5f7fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;

      :deep(.el-image) {
        width: 100%;
        height: 100%;
      }
    }

    .target-name {
      font-size: 14px;
      margin: 8px 0;
      text-align: center;
    }

    .slider-container {
      padding: 0 10px;
    }

    .accuracy-control {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 200px;
    margin-top: 40px;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
  }
}

:deep(.el-form-item__label) {
  font-size: 14px;
}
:deep(.el-upload-dragger) {
  padding: 20px 20px !important;
  background-color: transparent;
}

.border1 {
  border: 1px solid #dcdfe6;
}

</style>
